//
//  HMSettingViewController.m
//  HeartMark
//
//  Created by rimi on 2016/11/6.
//  Copyright © 2016年 黄华强. All rights reserved.
//


#import "HMSettingViewController.h"
#import "HMAlertView.h"
#import "HMFeedbackController.h"
#import "HMAboutController.h"
#import "HMInfomationController.h"
#import <AVOSCloud/AVOSCloud.h>
#import "HMSettingController.h"

@interface HMSettingViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) NSDictionary *allnames;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic, strong) UIButton *userIconBtn;
@property (nonatomic, strong)  UILabel *userNameLabel;
@property (nonatomic, copy) NSString *userName;
@property (nonatomic,strong) NSString *userIconUrl;
@property (nonatomic,copy) NSString *userId;
@property (nonatomic,copy) NSString *iconId;
@property (nonatomic,copy) AVObject *userIconObj;
@end

@implementation HMSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置UI
    [self setupUI];
    
    //静态cell的数据字典
    _allnames = @{@"0":@[@"个人信息"],@"1":@[@"关于我们",@"建议反馈"]};
    
    //注册重用cell
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"myCell"];
    //屏蔽多余的线
    self.tableView.tableFooterView = [[UIView alloc]init];
    //取消滚动效果
    self.tableView.bounces = false;
    //取消scrollView的自动偏移
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self loadData];
}

- (void)loadData {
    AVUser *currentUser = [AVUser currentUser];
    _userId = currentUser[@"objectId"];
    
    AVQuery *query = [AVQuery queryWithClassName:@"userIcon"];
    [query whereKey:@"userId" equalTo:_userId];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            _userIconObj = [objects lastObject];
            _userIconUrl = _userIconObj[@"iconUrl"];
            NSString *nickName = _userIconObj[@"userNickName"];
            if (!nickName||[nickName isEqualToString:@""]) {
                nickName = @"未设置用户昵称";
            }
            
            _userNameLabel.text = nickName;
            
            _iconId = _userIconObj[@"iconId"];
            AVFile *file = [AVFile fileWithURL:_userIconUrl];
            [file getDataInBackgroundWithBlock:^(NSData * _Nullable data, NSError * _Nullable error) {
                if (!error) {
                    [self.userIconBtn setImage:[UIImage imageWithData:data] forState:(UIControlStateNormal)];
                }
                
            }];
        }
    }];
    
}

- (void)setupUI {
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
    UIImage *newImage = [self iamgeWithImage:[UIImage imageNamed:@"bgImage"] scaledToSize:CGSizeMake(SCREEN_WIDTH, 200)];
    headView.backgroundColor = [UIColor colorWithPatternImage:newImage];
    
    _userIconBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2 - 40, 200/2 - 40, 90, 90)];
    _userIconBtn.layer.cornerRadius = 45;
    _userIconBtn.layer.masksToBounds = YES;
    [_userIconBtn setBackgroundImage:[UIImage imageNamed:@"默认头像"] forState:UIControlStateNormal];
    [_userIconBtn addTarget:self action:@selector(userIconClicked) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:_userIconBtn];
    
    _userNameLabel = [[UILabel alloc]initWithFrame:CGRectMake( SCREEN_WIDTH/2 - 100, _userIconBtn.frame.origin.y + _userIconBtn.bounds.size.height, 200, 44)];
    _userNameLabel.text = @"未设置用户昵称";
    _userNameLabel.textAlignment = NSTextAlignmentCenter;
    _userNameLabel.font = [UIFont systemFontOfSize:14];
    _userNameLabel.textColor = [UIColor whiteColor];
    [headView addSubview:_userNameLabel];
    
    self.tableView.tableHeaderView = headView;
}

#pragma mark --按钮点击回调
- (void)userIconClicked {
    
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //相机方法
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            self.imagePickerVc.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:self.imagePickerVc animated:YES completion:nil];
        }else{
            [HMAlertView bottomAlertView:@"打开相机失败"];
        }
        
    }];
    UIAlertAction *photoAlbum = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //相册方法
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
            self.imagePickerVc.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            [self presentViewController:self.imagePickerVc animated:YES completion:nil];
        }else {
            [HMAlertView bottomAlertView:@"打开相册失败"];
        }
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertVc addAction:camera];
    [alertVc addAction:photoAlbum];
    [alertVc addAction:cancel];
    
    [self presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark --表格视图相关方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return 2;
            break;
        
        default:
            return 0;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _allnames.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 8;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell" forIndexPath:indexPath];
    //设置样式
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    //int转String
    NSString *str = [NSString stringWithFormat:@"%ld", (long)indexPath.section];
    //获取数据字典的数组
    NSArray* arr = [_allnames valueForKey:str];
    cell.textLabel.text = arr[indexPath.row];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        HMInfomationController* infoVc = [[HMInfomationController alloc]init];
        infoVc.title = @"个人信息";
        infoVc.MyBlock = ^(NSString *myName) {
            if (_userIconObj) {
                [_userIconObj setObject:myName forKey:@"userNickName"];
                [_userIconObj saveEventually];
                
                
            } else {
                
                AVObject *userIconObj = [[AVObject alloc] initWithClassName:@"userIcon"];
                
                [userIconObj setObject:_userId forKey:@"userId"];
                [userIconObj setObject:myName forKey:@"userNickName"];
                [userIconObj saveEventually];
                
                
                _userIconObj = userIconObj;
            }

            
            _userNameLabel.text = myName;
        };
        infoVc.userName = _userIconObj[@"userNickName"];
        infoVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:infoVc animated:YES];
    }
    
    if (indexPath.section == 1 && indexPath.row == 0) {
        HMAboutController* aboutVc = [[HMAboutController alloc]init];
        aboutVc.title = @"关于我们";
        aboutVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:aboutVc animated:YES];
    }
    if (indexPath.section == 1 && indexPath.row == 1) {
        HMFeedbackController* feedbackVc = [[HMFeedbackController alloc]init];
        feedbackVc.hidesBottomBarWhenPushed = YES;
        feedbackVc.title = @"建议反馈";
        [self.navigationController pushViewController:feedbackVc animated:YES];
    }
    if (indexPath.section == 2 && indexPath.row == 0) {
        
        HMSettingController* setVc = [[HMSettingController alloc]init];
        setVc.title = @"设置";
        setVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:setVc animated:YES];
    }
    
}

#pragma mark --图片选择器代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage];
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
    }
    
    [_userIconBtn setImage:image forState:UIControlStateNormal];
    NSData *data = UIImagePNGRepresentation(image);
    //清除以前的图片
    AVObject *iconObject = [AVObject objectWithClassName:@"_File" objectId:_iconId];
    [iconObject deleteInBackground];
    //保存图片
    AVFile *file = [AVFile fileWithName:@"userIcon.png" data:data];
    [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            if (_userIconObj) {
                [_userIconObj setObject:file.url forKey:@"iconUrl"];
                [_userIconObj setObject:file.objectId forKey:@"iconId"];
                [_userIconObj saveEventually];
                _iconId = file.objectId;
                
            } else {
                
                AVObject *userIconObj = [[AVObject alloc] initWithClassName:@"userIcon"];
                [userIconObj setObject:file.url forKey:@"iconUrl"];
                [userIconObj setObject:_userId forKey:@"userId"];
                [userIconObj setObject:file.objectId forKey:@"iconId"];
                [userIconObj saveEventually];
                
                _iconId = file.objectId;
                _userIconObj = userIconObj;
            }

        } else {
            [HMAlertView bottomAlertView:@"头像上传失败"];
        }
        
    }];
    
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark --视图将要显示和将要消失
- (void)viewWillAppear:(BOOL)animated {
    //视图将要显示时隐藏导航栏
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    //视图将要消失显示导航栏
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (UIImage *)iamgeWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //上下文
    UIGraphicsBeginImageContext(newSize);
    //绘制
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    //获得新图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}


#pragma mark --懒加载
- (UIImagePickerController *)imagePickerVc{
    
    if (!_imagePickerVc) {
        _imagePickerVc = [[UIImagePickerController alloc]init];
        _imagePickerVc.allowsEditing = YES;
        _imagePickerVc.delegate = self;
    }
    return _imagePickerVc;
}


@end
